<template>
  <div class="container">
    <div class="head">
      <el-button type="primary" @click="dialogVisible = true">
        新增
      </el-button>
      <el-button type="primary" plain @click="exportData">导出数据</el-button>
      <el-button type="primary" plain @click="importData">
        导入数据
      </el-button>
      (<el-button link type="primary" style="margin-left: 0;" @click="downloadTemplate">下载模版</el-button>)
    </div>
    <div class="table-container">
      <el-table :data="tableData" height="100%" stripe border>
        <el-table-column type="index" label="序号" width="80" /> />
        <el-table-column prop="homonym" label="同音词" />
        <el-table-column prop="realWord" label="实际词" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editHomonym(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteHomonym(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑同音词' : '新增同音词'"
      width="500"
      :before-close="closeDialog"
    >
    <el-form ref="form" :model="formData" :rules="rules" label-width="auto"> 
      <el-form-item label="同音词" prop="homonym">
        <el-input v-model="formData.homonym" />
      </el-form-item>
      <el-form-item label="实际词" prop="realWord">
        <el-input v-model="formData.realWord" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
const tableData = ref([])

// 获取数据
const fetchData = async () => {
  try {
    const res = await fetch(`${API_BASE_URL}/homonyms`)
    const data = await res.json()
    tableData.value = Array.isArray(data) ? data : []
  } catch (e) {
    tableData.value = []
  }
}

onMounted(() => {
  fetchData()
})

const form = ref(null)
const rules = reactive({
  homonym: [
    { required: true, message: '请输入同音词', trigger: 'blur' },
  ],
  realWord: [
    { required: true, message: '请输入实际词', trigger: 'blur' },
  ],
})
const formData = reactive({
  homonym: '',
  realWord: ''
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const editingRow = ref(null)
const closeDialog = () => {
  dialogVisible.value = false
  isEdit.value = false
  editingRow.value = null
  formData.homonym = ''
  formData.realWord = ''
}
const submitForm = () => {
  if (!form.value) return
  form.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑
          const res = await fetch(`${API_BASE_URL}/homonyms`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              oldHomonym: editingRow.value.homonym,
              oldRealWord: editingRow.value.realWord,
              homonym: formData.homonym,
              realWord: formData.realWord
            })
          })
          const result = await res.json()
          if (res.ok) {
            ElMessage.success('编辑成功')
            closeDialog()
            await fetchData()
          } else {
            ElMessage.error(result.message || '编辑失败')
          }
        } else {
          // 新增
          const res = await fetch(`${API_BASE_URL}/homonyms`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              homonym: formData.homonym,
              realWord: formData.realWord
            })
          })
          const result = await res.json()
          if (res.ok) {
            ElMessage.success('新增成功')
            closeDialog()
            await fetchData()
          } else {
            ElMessage.error(result.message || '新增失败')
          }
        }
      } catch (e) {
        ElMessage.error('请求失败，请检查网络或服务器')
      }
    }
  })
}

const editHomonym = (row) => {
  isEdit.value = true
  editingRow.value = { ...row }
  formData.homonym = row.homonym
  formData.realWord = row.realWord
  dialogVisible.value = true
}

const deleteHomonym = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认删除同音词“${row.homonym}”吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 确认后执行删除
    const res = await fetch(`${API_BASE_URL}/homonyms`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        homonym: row.homonym,
        realWord: row.realWord
      })
    })
    const result = await res.json()
    if (res.ok) {
      ElMessage.success('删除成功')
      await fetchData()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    // 用户点击取消，不做任何操作
    if (error === 'cancel') {
      return
    }
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}
const exportData = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  try {
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(tableData.value, {
      header: ['homonym', 'realWord']
    })
    
    // 设置表头为中文
    XLSX.utils.sheet_add_aoa(worksheet, [['同音词', '实际词']], { origin: 'A1' })
    
    // 创建工作簿
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '同音词数据')
    
    // 导出文件
    const fileName = `同音词数据_${new Date().getTime()}.xlsx`
    XLSX.writeFile(workbook, fileName)
    
    ElMessage.success(`导出成功！共 ${tableData.value.length} 条数据`)
  } catch (e) {
    console.error('导出失败:', e)
    ElMessage.error('导出失败')
  }
}
const importData = () => {
  // 创建文件选择器
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (e) => {
    const file = e.target.files[0]
    if (!file) return
    
    try {
      // 读取文件
      const data = await file.arrayBuffer()
      const workbook = XLSX.read(data)
      
      // 读取第一个工作表
      const sheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[sheetName]
      
      // 转换为 JSON，跳过表头
      const jsonData = XLSX.utils.sheet_to_json(worksheet)
      
      if (jsonData.length === 0) {
        ElMessage.warning('Excel 文件中没有数据')
        return
      }
      
      // 转换为需要的格式
      const items = jsonData.map(row => ({
        homonym: row['同音词'] || row['homonym'] || '',
        realWord: row['实际词'] || row['realWord'] || ''
      }))
      
      // 批量导入
      const res = await fetch(`${API_BASE_URL}/homonyms/batch`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ items })
      })
      
      const result = await res.json()
      if (res.ok) {
        const msg = `导入完成！成功: ${result.successCount}，跳过: ${result.skipCount}，错误: ${result.errorCount}`
        ElMessage.success(msg)
        if (result.errors && result.errors.length > 0) {
          console.log('导入错误详情:', result.errors)
        }
        await fetchData()
      } else {
        ElMessage.error(result.message || '导入失败')
      }
    } catch (e) {
      console.error('导入失败:', e)
      ElMessage.error('导入失败，请检查文件格式')
    }
  }
  input.click()
}

const downloadTemplate = () => {
  const link = document.createElement('a')
  link.href = '/template.xlsx'
  link.download = '同音词导入模版.xlsx'
  link.click()
}
</script>

<style lang="scss" scoped>
.container{
    width: 100%;
    height: 100vh;
    box-sizing: border-box;
    padding: 20px;
    display: flex;
    flex-direction: column;
    .head{
      margin-bottom: 10px;
    }
    .table-container{
      height: calc(100% - 40px);
    }
 }
</style>
